﻿using IcsSEMCtrl.Db;
using IcsSEMCtrl.Global;
using IcsSEMCtrl.Service.Logger;
using IcsSEMCtrl.Util.Client;
using Lifter.Device;
using Lifter.Global.Device;
using Lifter.Utility;
using MiniExcelLibs;
using Sunny.UI;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using TKT.Lifter.CIM.Lifter.Device.Service;
using TKT.Lifter.CIM.Lifter.Global;
using TKT.Lifter.CIM.Lifter.Gui.Monitor.Popups;

namespace TKT.Lifter.CIM.Lifter.Gui.Monitor.Panels
{
    public partial class AllHistoryControl : UserControl
    {
        private Thread threadCommandSearch = null;
        private Thread threaAlarmdSearch = null;
        private Thread threadMaterialSearch = null;
        private Thread threadMonitorSearch = null;
        private bool tabPage1CancelFlag = false;
        private bool AlarmHistoryCancelFlag = false;
        private bool MonitorDataHistoryCancelFlag = false;
        private delegate void LogReadDelegate();
        private delegate void LogChartDelegate(List<string> rows);
        private delegate void AddCommandHistoryDataGrid(List<CommandHistoryDao> commandHistories);
        private delegate void AddAlarmHistoryDataGrid(List<AlarmHistoryDao> alarmHistories);
        private delegate void AddMaterialHistoryDataGrid(List<MaterialHistoryDao> materialHistories);
        private delegate void AddDataGrid(string data);
        private LifterSEM LftSem;
        List<CommandHistoryDao> CommandHistoryAllRows = new List<CommandHistoryDao>();
        List<AlarmHistoryDao> AlarmHistoryAllRows = new List<AlarmHistoryDao>();
        List<MaterialHistoryDao> MaterialHistoryAllRows = new List<MaterialHistoryDao>();
        List<string> MonitorDataRows = new List<string>();
        public delegate void page();
        DateTimeConverter dateTimeConverter = new DateTimeConverter();
        public AllHistoryControl()
        {
            InitializeComponent();
            DateInit();
            this.InitializeTransferHistoryDataGrid();
            this.InitializeMaterialHistoryDataGrid();
            this.InitializeAlarmHistoryDataGrid();
            //this.ClearUITime();
            try
            {
                this.LftSem = (LifterSEM)Naming.GetDeviceManager().GetDevice();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            //初始化权限
            InitPowerMenu();
        }
        /// <summary>
        /// 清除界面时间输入框的值
        /// </summary>
        public void ClearUITime()
        {
            this.LogStartTime.Text = "";
            this.LogEndTime.Text = "";
            this.LogAlarmStartTime.Text = "";
            this.LogAlarmEndTime.Text = "";
        }
        private void DateInit()
        {
            DateTime NowDay = new DateTime();
            NowDay = DateTime.Now;
            string startDate = NowDay.ToString("yyyy-MM-dd" + " 08:30:00");
            string endDate = NowDay.ToString("yyyy-MM-dd" + " 20:30:00");
            this.LogStartTime.Text = startDate;
            this.LogEndTime.Text = endDate;
            this.LogAlarmStartTime.Text = startDate;
            this.LogAlarmEndTime.Text = endDate;
            this.materialStartTime.Text = startDate;
            this.materialEndTime.Text = endDate;
        }
        /// <summary>
        /// 初始化页面权限
        /// </summary>
        public void InitPowerMenu()
        {
            List<MenuDao> menusOperation = GetMenuByPower(LftSem.UserPower);
            updatePowerForm(menusOperation);
            /*			if (LftSem.UserPower.Equals(enumUserManage.Operation.ToString()))
						{
							List<MenuDao> menusOperation = GetMenuByPower(enumUserManage.Operation.ToString());
							updatePowerForm(menusOperation);
						}
						else if (LftSem.UserPower.Equals(enumUserManage.Management.ToString()))
						{
							List<MenuDao> menusManagement = GetMenuByPower(enumUserManage.Management.ToString());
							updatePowerForm(menusManagement);
						}*/
        }
        private void updatePowerForm(List<MenuDao> menuDaos)
        {
            foreach (MenuDao menu in menuDaos)
            {
                if (menu.ENNAME.Equals("TransferCommandHistory"))
                {
                    if (menu.MENUDISPLAY.Equals("N"))
                    {
                        this.Controls["TableControl"].Controls.Remove(this.tabPage1);
                    }
                    else
                    {
                        if (!this.Controls["TableControl"].Controls.Contains(this.tabPage1))
                        {
                            this.Controls["TableControl"].Controls.Add(this.tabPage1);
                        }
                        if (menu.MENUUSE.Equals("N"))
                        {
                            this.Controls["TableControl"].Controls["tabPage1"].Enabled = false;
                        }
                        else
                        {
                            this.Controls["TableControl"].Controls["tabPage1"].Enabled = true;
                        }
                        if (this.LftSem.LanguageType.Equals("EN"))
                        {
                            this.Controls["TableControl"].Controls["tabPage1"].Text = menu.ENNAME;
                        }
                    }
                }
                if (menu.ENNAME.Equals("AlarmHistory"))
                {
                    if (menu.MENUDISPLAY.Equals("N"))
                    {
                        this.Controls["TableControl"].Controls.Remove(this.AlarmHistory);
                    }
                    else
                    {
                        if (!this.Controls["TableControl"].Controls.Contains(this.AlarmHistory))
                        {
                            this.Controls["TableControl"].Controls.Add(this.AlarmHistory);
                        }
                        if (menu.MENUUSE.Equals("N"))
                        {
                            this.Controls["TableControl"].Controls["AlarmHistory"].Enabled = false;
                        }
                        else
                        {
                            this.Controls["TableControl"].Controls["AlarmHistory"].Enabled = true;
                        }
                    }
                }
            }
        }
        private List<MenuDao> GetMenuByPower(string PowerName)
        {
            DBConnection dBConnection = DBControl.GetConnection();
            List<MenuDao> menuLists = new List<MenuDao>();
            string sqlString = string.Format("SELECT USERMENU.ENNAME,USERMENU.CNNAME,USERMENUPOWER.MENUDISPLAY,USERMENUPOWER.MENUUSE" +
                                             " FROM USERMENU,USERMENUPOWER " +
                                             " WHERE USERMENU.ENNAME = USERMENUPOWER.MENUNAME " +
                                             " AND USERMENU.PARENTID = (SELECT ID FROM USERMENU WHERE USERMENU.ENNAME = '{0}') " +
                                             " AND USERMENUPOWER.POWERNAME = '{1}'", this.Name, PowerName);
            SqlDataReader sqlDataReader = dBConnection.ExecuteQuery(sqlString);
            while (sqlDataReader.Read())
            {
                MenuDao menuDao = new MenuDao();
                menuDao.CNNAME = (string)sqlDataReader["CNNAME"];
                menuDao.ENNAME = (string)sqlDataReader["ENNAME"];
                menuDao.MENUDISPLAY = (string)sqlDataReader["MENUDISPLAY"];
                menuDao.MENUUSE = (string)sqlDataReader["MENUUSE"];
                menuLists.Add(menuDao);
            }
            if (sqlDataReader != null)
            {
                sqlDataReader.Close();
            }
            DBControl.RemoveDBConection(dBConnection);
            return menuLists;
        }
        private class MenuDao
        {
            public string ENNAME { get; set; }
            public string CNNAME { get; set; }
            public string MENUDISPLAY { get; set; }
            public string MENUUSE { get; set; }
        }
        
        private void InitializeTransferHistoryDataGrid()
        {
            try
            {
                this.commandDgv.AllowUserToAddRows = true;
                this.commandDgv.Columns.Add(new DataGridViewTextBoxColumn());
                this.commandDgv.Columns.Add(new DataGridViewTextBoxColumn());
                this.commandDgv.Columns.Add(new DataGridViewTextBoxColumn());
                this.commandDgv.Columns.Add(new DataGridViewTextBoxColumn());
                this.commandDgv.Columns.Add(new DataGridViewTextBoxColumn());
                this.commandDgv.Columns.Add(new DataGridViewTextBoxColumn());
                this.commandDgv.Columns.Add(new DataGridViewTextBoxColumn());
                this.commandDgv.Columns.Add(new DataGridViewTextBoxColumn());
                this.commandDgv.Columns.Add(new DataGridViewTextBoxColumn());
                this.commandDgv.Columns.Add(new DataGridViewTextBoxColumn());
                this.commandDgv.Columns[0].HeaderText = "序号";
                this.commandDgv.Columns[1].HeaderText = "指令ID";
                this.commandDgv.Columns[2].HeaderText = "物料ID";
                this.commandDgv.Columns[3].HeaderText = "指令类型";
                this.commandDgv.Columns[4].HeaderText = "创建类型";
                this.commandDgv.Columns[5].HeaderText = "起始地";
                this.commandDgv.Columns[6].HeaderText = "目的地";
                this.commandDgv.Columns[7].HeaderText = "搬送结果";
                this.commandDgv.Columns[8].HeaderText = "创建时间";
                this.commandDgv.Columns[9].HeaderText = "完成时间";

                this.commandDgv.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);

                //设置分页控件每页数量
                HistoryPagination.PageSize = Convert.ToInt32(this.PageSize.Value);
            }
            catch (Exception)
            {
            }
        }
        private void InitializeMaterialHistoryDataGrid()
        {
            try
            {
                this.DGVMaterial.AllowUserToAddRows = true;
                this.DGVMaterial.Columns.Add(new DataGridViewTextBoxColumn());
                this.DGVMaterial.Columns.Add(new DataGridViewTextBoxColumn());
                this.DGVMaterial.Columns.Add(new DataGridViewTextBoxColumn());
                this.DGVMaterial.Columns.Add(new DataGridViewTextBoxColumn());
                this.DGVMaterial.Columns.Add(new DataGridViewTextBoxColumn());
                this.DGVMaterial.Columns.Add(new DataGridViewTextBoxColumn());
                this.DGVMaterial.Columns.Add(new DataGridViewTextBoxColumn());
                this.DGVMaterial.Columns.Add(new DataGridViewTextBoxColumn());
                this.DGVMaterial.Columns.Add(new DataGridViewTextBoxColumn());
                this.DGVMaterial.Columns.Add(new DataGridViewTextBoxColumn());
                this.DGVMaterial.Columns.Add(new DataGridViewTextBoxColumn());
                this.DGVMaterial.Columns[0].HeaderText = "序号";
                this.DGVMaterial.Columns[1].HeaderText = "物料ID";
                this.DGVMaterial.Columns[2].HeaderText = "指令ID";
                this.DGVMaterial.Columns[3].HeaderText = "物料类型";
                this.DGVMaterial.Columns[4].HeaderText = "读取状态";
                this.DGVMaterial.Columns[5].HeaderText = "设备ID";
                this.DGVMaterial.Columns[6].HeaderText = "创建类型";
                this.DGVMaterial.Columns[7].HeaderText = "完成结果";
                this.DGVMaterial.Columns[8].HeaderText = "物料位置";
                this.DGVMaterial.Columns[9].HeaderText = "创建时间";
                this.DGVMaterial.Columns[10].HeaderText = "完成时间";

                this.DGVMaterial.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);

                //设置分页控件每页数量
                MaterialHistoryPagination.PageSize = Convert.ToInt32(this.PageSize.Value);
            }
            catch (Exception)
            {
            }
        }
        private void InitializeAlarmHistoryDataGrid()
        {
            try
            {
                this.DGVAlarm.AllowUserToAddRows = true;
                this.DGVAlarm.Columns.Add(new DataGridViewTextBoxColumn());
                this.DGVAlarm.Columns.Add(new DataGridViewTextBoxColumn());
                this.DGVAlarm.Columns.Add(new DataGridViewTextBoxColumn());
                this.DGVAlarm.Columns.Add(new DataGridViewTextBoxColumn());
                this.DGVAlarm.Columns.Add(new DataGridViewTextBoxColumn());
                this.DGVAlarm.Columns.Add(new DataGridViewTextBoxColumn());
                this.DGVAlarm.Columns.Add(new DataGridViewTextBoxColumn());
                this.DGVAlarm.Columns.Add(new DataGridViewTextBoxColumn());
                this.DGVAlarm.Columns.Add(new DataGridViewTextBoxColumn());
                this.DGVAlarm.Columns[0].HeaderText = "序列号";
                this.DGVAlarm.Columns[1].HeaderText = "报警ID";
                this.DGVAlarm.Columns[2].HeaderText = "报警代码";
                this.DGVAlarm.Columns[3].HeaderText = "报警内容";
                this.DGVAlarm.Columns[4].HeaderText = "报警置位";
                this.DGVAlarm.Columns[5].HeaderText = "造成原因";
                this.DGVAlarm.Columns[6].HeaderText = "解警措施";
                this.DGVAlarm.Columns[7].HeaderText = "创建时间";
                this.DGVAlarm.Columns[8].HeaderText = "清除时间";

                //this.DGVAlarm.Columns[0].Width = 50;
                this.DGVAlarm.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
                this.DGVAlarm.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                this.DGVAlarm.RowsDefaultCellStyle.WrapMode = DataGridViewTriState.False;
                //设置DataGridView文本居中
                this.DGVAlarm.RowsDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                this.DGVAlarm.AllowUserToAddRows = false;
                //设置分页控件每页数量
                AlarmHistoryPagination.PageSize = Convert.ToInt32(this.AlarmPageSize.Value);
            }
            catch (Exception)
            {
            }
        }
        public void LoadData()
        {
            CommandHistoryAllRows.Clear();
            if (this.threadCommandSearch == null)
            {
                this.threadCommandSearch = new Thread(new ThreadStart(this.TransferLogRead));
            }
            if (this.threadCommandSearch.ThreadState != ThreadState.Running)
            {
                if (this.threadCommandSearch.ThreadState == ThreadState.Stopped)
                {
                    this.threadCommandSearch = new Thread(new ThreadStart(this.TransferLogRead));
                    this.threadCommandSearch.Start();
                }
                else
                {
                    if (this.threadCommandSearch.ThreadState == ThreadState.Stopped)
                    {
                        this.threadCommandSearch.Start();
                    }
                    else
                    {
                        if (this.threadCommandSearch.ThreadState == ThreadState.Unstarted)
                        {
                            this.threadCommandSearch.Start();
                        }
                    }
                }
            }
        }
        private void btSearch_Click(object sender, EventArgs e)
        {
            LoadData();
        }
        private void TransferLogRead()
        {
            try
            {
                base.BeginInvoke(new AllHistoryControl.LogReadDelegate(this.StartSearch));
          
                string logStartTime = this.LogStartTime.Text;
                string logEndTime = this.LogEndTime.Text;
                string keyWord = this.tbKeyWord.Text;

                CommandHistoryAllRows = this.GetCommandHistorys(logStartTime, logEndTime, keyWord);

                //设置分页信息
                //设置分页控件总数
                HistoryPagination.BeginInvoke(new page(() =>
                {
                    {
                        HistoryPagination.TotalCount = CommandHistoryAllRows.Count();//AlarmsList.Count();
                        HistoryPagination.ActivePage = 1;
                    }
                }));
                base.BeginInvoke(new AllHistoryControl.LogReadDelegate(this.EndSearch));
            }
            catch (Exception ex)
            {
                PopupNotice.DialogPopups("查询失败，错误代码 :" + ex.Message, "Query failed with error code: " + ex.Message, enumPopupsType.Error);
                LogHelper.loggerError("查询失败",ex);
                base.BeginInvoke(new AllHistoryControl.LogReadDelegate(this.EndSearch));
                return;
            }
        }
        /// <summary>
        /// 从数据库表中，获取指令的历史记录
        /// </summary>
        /// <returns></returns>
        public List<CommandHistoryDao> GetCommandHistorys(string startTime, string endTime, string keyWord)
        {
            List<CommandHistoryDao> commandHistoryDaos = new List<CommandHistoryDao>();
            SqlDataReader sqlDataReader = null;
            try
            {
                DBConnection dBConnection = DBControl.GetConnection();
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.Append("SELECT * FROM COMMANDHISTORY WHERE 1 = 1 ");
                if (!string.IsNullOrEmpty(startTime))
                {
                    stringBuilder.Append($" AND CREATETIME >= '{startTime}'");
                }
                if (!string.IsNullOrEmpty(endTime))
                {
                    stringBuilder.Append($" AND CREATETIME <= '{endTime}'");
                }
                if (!string.IsNullOrEmpty(keyWord))
                {
                    stringBuilder.Append($" AND COMMANDID LIKE '%{keyWord}%'");
                }
                sqlDataReader = dBConnection.ExecuteQuery(stringBuilder.ToString());
                while (sqlDataReader.Read())
                {
                    CommandHistoryDao commandHistoryDao = new CommandHistoryDao();
                    commandHistoryDao.CommandID = sqlDataReader["COMMANDID"].ToString();
                    commandHistoryDao.MaterialID = sqlDataReader["MATERIALID"].ToString();
                    commandHistoryDao.CommandType = sqlDataReader["COMMANDTYPE"].ToString();

                    commandHistoryDao.CreateCommandType = sqlDataReader["CREATECOMMANDTYPE"].ToString();
                    commandHistoryDao.Source = sqlDataReader["SOURCE"].ToString();
                    commandHistoryDao.Dest = sqlDataReader["DEST"].ToString();

                    commandHistoryDao.CreateTime = sqlDataReader["CREATETIME"].ToString();
                    commandHistoryDao.CompleteTime = sqlDataReader["COMPLETETIME"].ToString();
                    commandHistoryDao.TransferResult = sqlDataReader["TRANSFERRERULT"].ToString();

                    commandHistoryDaos.Add(commandHistoryDao);
                }
                if (sqlDataReader != null)
                {
                    sqlDataReader.Close();
                }
            }
            catch (Exception ex)
            {
                LogHelper.loggerError("查询commandHistory时报错",ex);
                PopupNotice.DialogPopups("查询失败，错误代码 :" + ex.Message, "Query failed with error code: " + ex.Message, enumPopupsType.Error);
            }
            if (sqlDataReader != null)
            {
                sqlDataReader.Close();
            }
            return commandHistoryDaos;
        }
        /// <summary>
        /// 从数据库表中，获取报警的历史记录
        /// </summary>
        /// <returns></returns>
        public List<AlarmHistoryDao> GetAlarmHistorys(string startTime, string endTime, string keyWord)
        {
            List<AlarmHistoryDao> alarmHistoryDaos = new List<AlarmHistoryDao>();
            SqlDataReader sqlDataReader = null;
            try
            {
                DBConnection dBConnection = DBControl.GetConnection();
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.Append("SELECT * FROM ALARMHISTORY WHERE 1 = 1 ");
                if (!string.IsNullOrEmpty(startTime))
                {
                    stringBuilder.Append($" AND CREATETIME >= '{startTime}'");
                }
                if (!string.IsNullOrEmpty(endTime))
                {
                    stringBuilder.Append($" AND CREATETIME <= '{endTime}'");
                }
                if (!string.IsNullOrEmpty(keyWord))
                {
                    stringBuilder.Append($" AND ALID LIKE '%{keyWord}%'");
                }
                sqlDataReader = dBConnection.ExecuteQuery(stringBuilder.ToString());
                while (sqlDataReader.Read())
                {
                    AlarmHistoryDao alarmHistoryDao = new AlarmHistoryDao();
                    alarmHistoryDao.AlarmID = sqlDataReader["ALID"].ToString();
                    alarmHistoryDao.AlarmCode = sqlDataReader["ALCD"].ToString();
                    alarmHistoryDao.AlarmText = sqlDataReader["ALTX"].ToString();

                    alarmHistoryDao.Subsystem = sqlDataReader["SUBSYSTEM"].ToString();
                    alarmHistoryDao.UnitName = sqlDataReader["UNITNAME"].ToString();
                    alarmHistoryDao.AlarmCase = sqlDataReader["CAUSE"].ToString();

                    alarmHistoryDao.Solution = sqlDataReader["SOLUTION"].ToString();
                    alarmHistoryDao.CreateTime = sqlDataReader["CREATETIME"].ToString();
                    alarmHistoryDao.ClearTime = sqlDataReader["CLEARTIME"].ToString();

                    alarmHistoryDaos.Add(alarmHistoryDao);
                }
            }
            catch (Exception ex)
            {
                LogHelper.loggerError("查询alarmHistory时报错", ex);
                PopupNotice.DialogPopups("查询失败，错误代码 :" + ex.Message, "Query failed with error code: " + ex.Message, enumPopupsType.Error);
            }
            if (sqlDataReader != null)
            {
                sqlDataReader.Close();
            }
            return alarmHistoryDaos;
        }
        /// <summary>
        /// 从数据库表中，获取物料的历史记录
        /// </summary>
        /// <returns></returns>
        public List<MaterialHistoryDao> GetMaterialHistorys(string startTime, string endTime, string keyWord)
        {
            List<MaterialHistoryDao> materialHistoryDaos = new List<MaterialHistoryDao>();
            SqlDataReader sqlDataReader = null;
            try
            {
                DBConnection dBConnection = DBControl.GetConnection();
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.Append("SELECT * FROM MATERIALHISTORY WHERE 1 = 1 ");
                if (!string.IsNullOrEmpty(startTime))
                {
                    stringBuilder.Append($" AND CREATETIME >= '{startTime}'");
                }
                if (!string.IsNullOrEmpty(endTime))
                {
                    stringBuilder.Append($" AND CREATETIME <= '{endTime}'");
                }
                if (!string.IsNullOrEmpty(keyWord))
                {
                    stringBuilder.Append($" AND MATERIALID LIKE '%{keyWord}%'");
                }
                sqlDataReader = dBConnection.ExecuteQuery(stringBuilder.ToString());
                while (sqlDataReader.Read())
                {
                    MaterialHistoryDao materialHistoryDao = new MaterialHistoryDao();
                    materialHistoryDao.MaterialID = sqlDataReader["MATERIALID"].ToString();
                    materialHistoryDao.CommandID = sqlDataReader["COMMANDID"].ToString();
                    materialHistoryDao.MaterialType = sqlDataReader["MATERIALTYPE"].ToString();

                    materialHistoryDao.IdreadState = sqlDataReader["IDREADSTATE"].ToString();
                    materialHistoryDao.HostName = sqlDataReader["HOSTNAME"].ToString();
                    materialHistoryDao.CreateType = sqlDataReader["CREATETYPE"].ToString();

                    materialHistoryDao.CreateTime = sqlDataReader["CREATETIME"].ToString();
                    materialHistoryDao.CompleteTime = sqlDataReader["COMPLETETIME"].ToString();
                    materialHistoryDao.CompleteResult = sqlDataReader["COMPLETERESULT"].ToString();
                    materialHistoryDao.MaterialLoc = sqlDataReader["MATERIALOC"].ToString();

                    materialHistoryDaos.Add(materialHistoryDao);
                }
            }
            catch (Exception ex)
            {
                LogHelper.loggerError("查询materialHistory时报错", ex);
                PopupNotice.DialogPopups("查询失败，错误代码 :" + ex.Message, "Query failed with error code: " + ex.Message, enumPopupsType.Error);
            }
            if (sqlDataReader != null)
            {
                sqlDataReader.Close();
            }
            return materialHistoryDaos;
        }
        private void uiPagination1_PageChanged(object sender, object pagingSource, int pageIndex, int count)
        {
            if (HistoryPagination.TotalCount >= pageIndex * count)
            {
                List<CommandHistoryDao> commandHistories = this.CommandHistoryAllRows.GetRange((pageIndex - 1) * count, count);
                LoadCommandHistoryData(commandHistories);
            }
            else
            {
                List<CommandHistoryDao> commandHistories = CommandHistoryAllRows.GetRange((pageIndex - 1) * count, (HistoryPagination.TotalCount - ((pageIndex - 1) * count)));
                LoadCommandHistoryData(commandHistories);
            }
        }
        public void LoadCommandHistoryData(List<CommandHistoryDao> rows)
        {
            commandDgv.Rows.Clear();
            base.BeginInvoke(new AllHistoryControl.AddCommandHistoryDataGrid(this.AddCommandHistoryLogData), rows);
        }
        public void LoadAlarmData(List<AlarmHistoryDao> rows)
        {
            DGVAlarm.Rows.Clear();
            base.BeginInvoke(new AllHistoryControl.AddAlarmHistoryDataGrid(this.AddAlarmData), rows);
        }
        public void LoadMaterialHistoryData(List<MaterialHistoryDao> rows)
        {
            DGVMaterial.Rows.Clear();
            base.BeginInvoke(new AllHistoryControl.AddMaterialHistoryDataGrid(this.AddMaterialHistoryLogData), rows);
        }
        private void EndSearch()
        {
            this.gpUserOperation.Enabled = true;
            this.commandDgv.Enabled = true;
            //this.panelProgress.SendToBack();
            this.commandDgv.Sort(this.commandDgv.Columns[0], ListSortDirection.Descending);
            foreach (DataGridViewRow dataGridViewRow in this.commandDgv.SelectedRows)
            {
                dataGridViewRow.Selected = false;
            }
        }
        private void EndAlarmSearch()
        {
            this.gpUserAlarmOperation.Enabled = true;
            this.DGVAlarm.Enabled = true;
            this.DGVAlarm.Sort(this.DGVAlarm.Columns[0], ListSortDirection.Descending);
            foreach (DataGridViewRow dataGridViewRow in this.DGVAlarm.SelectedRows)
            {
                dataGridViewRow.Selected = false;
            }
        }
        private void EndMaterialSearch()
        {
            this.gpUserMaterialOperation.Enabled = true;
            this.DGVMaterial.Enabled = true;
            this.DGVMaterial.Sort(this.DGVMaterial.Columns[0], ListSortDirection.Descending);
            foreach (DataGridViewRow dataGridViewRow in this.DGVMaterial.SelectedRows)
            {
                dataGridViewRow.Selected = false;
            }
        }
        private void AddCommandHistoryLogData(List<CommandHistoryDao> commandHistories)
        {
            try
            {
                int index = 0;
                int rowNum = 1;
                if (commandHistories != null && commandHistories.Count() > 0)
                {
                    this.commandDgv.RowCount = commandHistories.Count();
                    foreach (CommandHistoryDao commandHistory in commandHistories)
                    {
                        this.commandDgv.Rows[index].Cells[0].Value = rowNum;
                        this.commandDgv.Rows[index].Cells[1].Value = commandHistory.CommandID;
                        this.commandDgv.Rows[index].Cells[2].Value = commandHistory.MaterialID;
                        this.commandDgv.Rows[index].Cells[3].Value = commandHistory.CommandType;
                        this.commandDgv.Rows[index].Cells[4].Value = commandHistory.CreateCommandType;
                        this.commandDgv.Rows[index].Cells[5].Value = commandHistory.Source;
                        this.commandDgv.Rows[index].Cells[6].Value = commandHistory.Dest;
                        this.commandDgv.Rows[index].Cells[7].Value = commandHistory.TransferResult;
                        this.commandDgv.Rows[index].Cells[8].Value = commandHistory.CreateTime;
                        this.commandDgv.Rows[index].Cells[9].Value = commandHistory.CompleteTime;
                        index++;
                        rowNum++;
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.loggerError("在查询指令历史表，更新界面时报错",ex);
            }
        }
        private void AddMaterialHistoryLogData(List<MaterialHistoryDao> materialHistoryDaos)
        {
            try
            {
                int index = 0;
                int rowNum = 1;
                if (materialHistoryDaos != null && materialHistoryDaos.Count() > 0)
                {
                    this.DGVMaterial.RowCount = materialHistoryDaos.Count();
                    foreach (MaterialHistoryDao materialHistory in materialHistoryDaos)
                    {
                        this.DGVMaterial.Rows[index].Cells[0].Value = rowNum;
                        this.DGVMaterial.Rows[index].Cells[1].Value = materialHistory.MaterialID;
                        this.DGVMaterial.Rows[index].Cells[2].Value = materialHistory.CommandID;
                        this.DGVMaterial.Rows[index].Cells[3].Value = materialHistory.MaterialType;
                        this.DGVMaterial.Rows[index].Cells[4].Value = materialHistory.IdreadState;
                        this.DGVMaterial.Rows[index].Cells[5].Value = materialHistory.HostName;
                        this.DGVMaterial.Rows[index].Cells[6].Value = materialHistory.CreateType;
                        this.DGVMaterial.Rows[index].Cells[7].Value = materialHistory.CompleteResult;
                        this.DGVMaterial.Rows[index].Cells[8].Value = materialHistory.MaterialLoc;
                        this.DGVMaterial.Rows[index].Cells[9].Value = materialHistory.CreateTime;
                        this.DGVMaterial.Rows[index].Cells[10].Value = materialHistory.CompleteTime;
                        index++;
                        rowNum++;
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.loggerError("在查询物料历史表，更新界面时报错", ex);
            }
        }
        private void AddAlarmData(List<AlarmHistoryDao> alarmHistories)
        {
            try
            {
                int index = 0;
                int rowNum = 1;
                if (alarmHistories != null && alarmHistories.Count() > 0)
                {
                    this.DGVAlarm.RowCount = alarmHistories.Count();
                    foreach (AlarmHistoryDao alarmHistoryDao in alarmHistories)
                    {
                        this.DGVAlarm.Rows[index].Cells[0].Value = rowNum;
                        this.DGVAlarm.Rows[index].Cells[1].Value = alarmHistoryDao.AlarmID;
                        this.DGVAlarm.Rows[index].Cells[2].Value = alarmHistoryDao.AlarmCode;
                        this.DGVAlarm.Rows[index].Cells[3].Value = alarmHistoryDao.AlarmText;
                        this.DGVAlarm.Rows[index].Cells[4].Value = alarmHistoryDao.UnitName;
                        this.DGVAlarm.Rows[index].Cells[5].Value = alarmHistoryDao.AlarmCase;
                        this.DGVAlarm.Rows[index].Cells[6].Value = alarmHistoryDao.Solution;
                        this.DGVAlarm.Rows[index].Cells[7].Value = alarmHistoryDao.CreateTime;
                        this.DGVAlarm.Rows[index].Cells[8].Value = alarmHistoryDao.ClearTime;
                        index++;
                        rowNum++;
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.loggerError("在查询报警历史表，更新界面时报错", ex);
            }
        }
        
        private void StartSearch()
        {
            //this.labelMessage.Text = "正在查询数据。请稍等。";
            this.commandDgv.Rows.Clear();
            this.gpUserOperation.Enabled = false;
            this.gpUserOperation.Enabled = false;
        }

        private void AlarmStartSearch()
        {
            //this.labelMessage.Text = "正在查询数据。请稍等。";
            this.DGVAlarm.Rows.Clear();
            this.gpUserAlarmOperation.Enabled = false;
            this.gpUserAlarmOperation.Enabled = false;
        }
        private void MaterialStartSearch()
        {
            //this.labelMessage.Text = "正在查询数据。请稍等。";
            this.DGVMaterial.Rows.Clear();
            this.gpUserMaterialOperation.Enabled = false;
            this.gpUserMaterialOperation.Enabled = false;
        }
        private void PageSize_ValueChanged(object sender, int value)
        {
            //设置分页控件每页数量
            HistoryPagination.PageSize = Convert.ToInt32(this.PageSize.Value);
        }

        private void btExportLog_Click(object sender, EventArgs e)
        {
            if (this.commandDgv.Rows.Count <= 0)
            {
                PopupNotice.DialogPopups("请先查询历史记录", "Please check the history first", enumPopupsType.Warning);
            }
            else
            {
                if (this.commandDgv.SelectedRows.Count == 0)
                {
                    PopupNotice.DialogPopups("请选择要保存的部分", "Please select the section to save", enumPopupsType.Warning);
                }
                else
                {
                    //new Thread(new ParameterizedThreadStart(this.SaveCommandToCVS)).Start(false);
                    this.SaveCommandToCVS(false);
                }
            }
        }
        private async void SaveCommandToCVS(bool isAllExport)
        {
            string directory = "";
            if (DirEx.SelectDirEx("浏览文件夹", ref directory))
            {
                string filePath = $"{directory}CommandHistory-{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";
                
                try
                {
                    //全部导出
                    if (isAllExport)
                    {
                        await this.ExportCommandHistoryToExcelAsync(filePath, this.CommandHistoryAllRows);
                        PopupNotice.DialogPopups("导出指令历史记录成功", "Export command history successful", enumPopupsType.OK);
                        LogHelper.operationLogger($"用户[{this.LftSem.UserName}]导出指令历史记录成功.");
                        LftSem.InsertUserOperation(LftSem.UserName, $"用户[{this.LftSem.UserName}]导出指令历史记录成功.");
                    }
                    else
                    {
                        if (commandDgv.SelectedRows.Count > 0)
                        {
                            List<CommandHistoryDao> commandHistoriesBySelect = new List<CommandHistoryDao>();

                            foreach (DataGridViewRow dataGridViewRow in commandDgv.SelectedRows)
                            {
                                CommandHistoryDao commandHistory = new CommandHistoryDao();
                                commandHistory.CommandID = dataGridViewRow.Cells[1].Value.ToString();
                                commandHistory.MaterialID = dataGridViewRow.Cells[2].Value.ToString();
                                commandHistory.CommandType = dataGridViewRow.Cells[3].Value.ToString();

                                commandHistory.CreateCommandType = dataGridViewRow.Cells[4].Value.ToString();
                                commandHistory.Source = dataGridViewRow.Cells[5].Value.ToString();
                                commandHistory.Dest = dataGridViewRow.Cells[6].Value.ToString();

                                commandHistory.CreateTime = dataGridViewRow.Cells[7].Value.ToString();
                                commandHistory.CompleteTime = dataGridViewRow.Cells[8].Value.ToString();
                                commandHistory.TransferResult = dataGridViewRow.Cells[9].Value.ToString();
                                commandHistoriesBySelect.Add(commandHistory);
                            }

                            await this.ExportCommandHistoryToExcelAsync(filePath, commandHistoriesBySelect);
                            PopupNotice.DialogPopups("导出指令历史记录成功", "Export command history successful", enumPopupsType.OK);
                            LogHelper.operationLogger($"用户[{this.LftSem.UserName}]导出指令历史记录成功.");
                            LftSem.InsertUserOperation(LftSem.UserName, $"用户[{this.LftSem.UserName}]导出指令历史记录成功.");
                        }
                    }
                }
                catch (Exception ex)
                {
                    PopupNotice.DialogPopups($"导出指令历史记录失败，{ex}", $"Export command history failed,{ex}", enumPopupsType.Warning);
                    LogHelper.loggerError($"导出指令历史记录失败", ex);
                }
            }
        }
        private async void SaveAlarmToCVS(bool isAllExport)
        {
            string directory = "";
            if (DirEx.SelectDirEx("浏览文件夹", ref directory))
            {
                string filePath = $"{directory}AlarmHistory-{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";

                try
                {
                    //全部导出
                    if (isAllExport)
                    {
                        await this.ExportAlarmHistoryToExcelAsync(filePath, this.AlarmHistoryAllRows);
                        PopupNotice.DialogPopups("导出报警历史记录成功", "Export Alarm history successful", enumPopupsType.OK);
                        LogHelper.operationLogger($"用户[{this.LftSem.UserName}]导出报警历史记录成功.");
                        LftSem.InsertUserOperation(LftSem.UserName, $"用户[{this.LftSem.UserName}]导出报警历史记录成功.");
                    }
                    else
                    {
                        if (DGVAlarm.SelectedRows.Count > 0)
                        {
                            List<AlarmHistoryDao> alarmHistoryDaos = new List<AlarmHistoryDao>();

                            foreach (DataGridViewRow dataGridViewRow in DGVAlarm.SelectedRows)
                            {
                                AlarmHistoryDao alarmHistory = new AlarmHistoryDao();
                                alarmHistory.AlarmID = dataGridViewRow.Cells[1].Value.ToString();
                                alarmHistory.AlarmCode = dataGridViewRow.Cells[2].Value.ToString();
                                alarmHistory.AlarmText = dataGridViewRow.Cells[3].Value.ToString();
                                alarmHistory.Subsystem = dataGridViewRow.Cells[4].Value.ToString();
                                alarmHistory.UnitName = dataGridViewRow.Cells[4].Value.ToString();
                                alarmHistory.AlarmCase = dataGridViewRow.Cells[5].Value.ToString();

                                alarmHistory.Solution = dataGridViewRow.Cells[6].Value.ToString();
                                alarmHistory.CreateTime = dataGridViewRow.Cells[7].Value.ToString();
                                alarmHistory.ClearTime = dataGridViewRow.Cells[8].Value.ToString();
                                alarmHistoryDaos.Add(alarmHistory);
                            }

                            await this.ExportAlarmHistoryToExcelAsync(filePath, alarmHistoryDaos);
                            PopupNotice.DialogPopups("导出报警历史记录成功", "Export Alarm history successful", enumPopupsType.OK);
                            LogHelper.operationLogger($"用户[{this.LftSem.UserName}]导出报警历史记录成功.");
                            LftSem.InsertUserOperation(LftSem.UserName, $"用户[{this.LftSem.UserName}]导出报警历史记录成功.");
                        }
                    }
                }
                catch (Exception ex)
                {
                    PopupNotice.DialogPopups($"导出报警历史记录失败，{ex}", $"Export Alarm history failed,{ex}", enumPopupsType.Warning);
                    LogHelper.loggerError($"导出报警历史记录失败", ex);
                }
            }
        }
        private async void SaveMaterialToCVS(bool isAllExport)
        {
            string directory = "";
            if (DirEx.SelectDirEx("浏览文件夹", ref directory))
            {
                string filePath = $"{directory}MaterialHistory-{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";

                try
                {
                    //全部导出
                    if (isAllExport)
                    {
                        await this.ExportMaterialHistoryToExcelAsync(filePath, this.MaterialHistoryAllRows);
                        PopupNotice.DialogPopups("导出物料历史记录成功", "Export Material history successful", enumPopupsType.OK);
                        string message = $"用户[{this.LftSem.UserName}]导出物料历史记录成功.";
                        LogHelper.operationLogger(message);
                        LftSem.InsertUserOperation(LftSem.UserName, message);
                    }
                    else
                    {
                        if (DGVMaterial.SelectedRows.Count > 0)
                        {
                            List<MaterialHistoryDao> materialHistories = new List<MaterialHistoryDao>();

                            foreach (DataGridViewRow dataGridViewRow in DGVMaterial.SelectedRows)
                            {
                                MaterialHistoryDao materialHistory = new MaterialHistoryDao();
                                materialHistory.MaterialID = dataGridViewRow.Cells[1].Value.ToString();
                                materialHistory.CommandID = dataGridViewRow.Cells[2].Value.ToString();
                                materialHistory.MaterialType = dataGridViewRow.Cells[3].Value.ToString();

                                materialHistory.IdreadState = dataGridViewRow.Cells[4].Value.ToString();
                                materialHistory.HostName = dataGridViewRow.Cells[5].Value.ToString();
                                materialHistory.CreateType = dataGridViewRow.Cells[6].Value.ToString();

                                materialHistory.CreateTime = dataGridViewRow.Cells[7].Value.ToString();
                                materialHistory.CompleteTime = dataGridViewRow.Cells[8].Value.ToString();
                                materialHistory.CompleteResult = dataGridViewRow.Cells[9].Value.ToString();
                                materialHistory.MaterialLoc = dataGridViewRow.Cells[10].Value.ToString();
                                materialHistories.Add(materialHistory);
                            }

                            await this.ExportMaterialHistoryToExcelAsync(filePath, materialHistories);
                            PopupNotice.DialogPopups("导出物料历史记录成功", "Export Material history successful", enumPopupsType.OK);
                            LogHelper.operationLogger($"用户[{this.LftSem.UserName}]导出物料历史记录成功.");
                            LftSem.InsertUserOperation(LftSem.UserName, $"用户[{this.LftSem.UserName}]导出物料历史记录成功.");
                        }
                    }
                }
                catch (Exception ex)
                {
                    PopupNotice.DialogPopups($"导出物料历史记录失败，{ex}", $"Export Alarm history failed,{ex}", enumPopupsType.Warning);
                    LogHelper.loggerError($"导出物料历史记录失败", ex);
                }
            }
        }
        private void StartAlarmSave()
        {
            this.DGVAlarm.Enabled = false;
            this.gpUserAlarmOperation.Enabled = false;
        }
        private void EndAlarmSave()
        {
            this.gpUserAlarmOperation.Enabled = true;
            this.DGVAlarm.Enabled = true;
        }
        private void tbKeyWord_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Return)
            {
                this.btSearch_Click(this, null);
            }
        }

        private void btAlarmSearch_Click(object sender, EventArgs e)
        {
            AlarmHistoryAllRows.Clear();
            if (this.threaAlarmdSearch == null)
            {
                this.threaAlarmdSearch = new Thread(new ThreadStart(this.AlarmHistoryRead));
            }
            if (this.threaAlarmdSearch.ThreadState != ThreadState.Running)
            {
                if (this.threaAlarmdSearch.ThreadState == ThreadState.Stopped)
                {
                    this.threaAlarmdSearch = new Thread(new ThreadStart(this.AlarmHistoryRead));
                    this.threaAlarmdSearch.Start();
                }
                else if (this.threaAlarmdSearch.ThreadState == ThreadState.Stopped)
                {
                    this.threaAlarmdSearch.Start();
                }
                else if (this.threaAlarmdSearch.ThreadState == ThreadState.Unstarted)
                {
                    this.threaAlarmdSearch.Start();
                }
            }
        }
        private void AlarmHistoryRead()
        {
            try
            {
                base.BeginInvoke(new AllHistoryControl.LogReadDelegate(this.AlarmStartSearch));
               
                string logAlarmStartTime = this.LogAlarmStartTime.Text;
                string logAlarmEndTime = this.LogAlarmEndTime.Text;
                string alarmKeyWord = this.tbAlarmKeyWord.Text;

                AlarmHistoryAllRows = this.GetAlarmHistorys(logAlarmStartTime, logAlarmEndTime, alarmKeyWord);
                //设置分页信息
                //设置分页控件总数
                AlarmHistoryPagination.BeginInvoke(new page(() =>
                {
                    {
                        AlarmHistoryPagination.TotalCount = AlarmHistoryAllRows.Count();//AlarmsList.Count();
                        AlarmHistoryPagination.ActivePage = 1;
                    }
                }));
                base.BeginInvoke(new AllHistoryControl.LogReadDelegate(this.EndAlarmSearch));
            }
            catch (Exception ex)
            {
                PopupNotice.DialogPopups("查询失败，错误代码 :" + ex.Message, "Query failed with error code: " + ex.Message, enumPopupsType.Error);
                LogHelper.loggerError("查询失败", ex);
                base.BeginInvoke(new AllHistoryControl.LogReadDelegate(this.EndSearch));
                return;
            }
        }
        private void MaterialHistoryRead()
        {
            try
            {
                base.BeginInvoke(new AllHistoryControl.LogReadDelegate(this.MaterialStartSearch));

                string materialStartTime = this.materialStartTime.Text;
                string materialEndTime = this.materialEndTime.Text;
                string materialKeyWord = this.materialKeyWord.Text;

                MaterialHistoryAllRows = this.GetMaterialHistorys(materialStartTime, materialEndTime, materialKeyWord);
                //设置分页信息
                //设置分页控件总数
                MaterialHistoryPagination.BeginInvoke(new page(() =>
                {
                    {
                        MaterialHistoryPagination.TotalCount = MaterialHistoryAllRows.Count();//AlarmsList.Count();
                        MaterialHistoryPagination.ActivePage = 1;
                    }
                }));
                base.BeginInvoke(new AllHistoryControl.LogReadDelegate(this.EndMaterialSearch));
            }
            catch (Exception ex)
            {
                PopupNotice.DialogPopups("查询失败，错误代码 :" + ex.Message, "Query failed with error code: " + ex.Message, enumPopupsType.Error);
                LogHelper.loggerError("查询失败", ex);
                base.BeginInvoke(new AllHistoryControl.LogReadDelegate(this.EndSearch));
                return;
            }
        }
        
        private void tbAlarmKeyWord_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Return)
            {
                this.btAlarmSearch_Click(this, null);
            }
        }

        private void AlarmHistoryPagination_PageChanged(object sender, object pagingSource, int pageIndex, int count)
        {
            if (AlarmHistoryPagination.TotalCount >= pageIndex * count)
            {
                List<AlarmHistoryDao> rows = AlarmHistoryAllRows.GetRange((pageIndex - 1) * count, count);
                LoadAlarmData(rows);
            }
            else
            {
                List<AlarmHistoryDao> rows = AlarmHistoryAllRows.GetRange((pageIndex - 1) * count, (AlarmHistoryPagination.TotalCount - ((pageIndex - 1) * count)));
                LoadAlarmData(rows);
            }
        }

        private void AlarmPageSize_ValueChanged(object sender, int value)
        {
            //设置分页控件每页数量
            AlarmHistoryPagination.PageSize = Convert.ToInt32(this.AlarmPageSize.Value);
        }

        private void btAlarmExportLog_Click(object sender, EventArgs e)
        {
            if (this.DGVAlarm.Rows.Count <= 0)
            {
                PopupNotice.DialogPopups("没有可保存的数据！！！", "There is no data to save!!!", enumPopupsType.Warning);
            }
            else
            {
                if (this.DGVAlarm.SelectedRows.Count == 0)
                {
                    PopupNotice.DialogPopups("请选择要保存的部分。[CTRL-A]为全选！！！", "Please select the section to save. [CTRL-A] Select All!!!", enumPopupsType.Warning);
                }
                else
                {
                    //new Thread(new ParameterizedThreadStart(this.SaveAlarmToCVS)).Start(false);
                    this.SaveAlarmToCVS(false);
                }
            }
        }
        
        private void TableControl_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.DateInit();
            //this.ClearUITime();
        }

        private void btExportAllLog_Click(object sender, EventArgs e)
        {
            if (this.commandDgv.Rows.Count <= 0 && this.CommandHistoryAllRows.Count <= 0)
            {
                UIMessageDialog.ShowMessageDialog("请先查询历史记录", UILocalize.WarningTitle, showCancelButton: false, UIStyle.Orange, false, false);
            }
            else
            {
                //new Thread(new ParameterizedThreadStart(this.SaveCommandToCVS)).Start(true);
                this.SaveCommandToCVS(true);
            }
        }

        private void btAlarmExportAllLog_Click(object sender, EventArgs e)
        {
            if (this.DGVAlarm.Rows.Count <= 0 || this.AlarmHistoryAllRows.Count <= 0)
            {
                UIMessageDialog.ShowMessageDialog("没有可保存的数据！！！", UILocalize.WarningTitle, showCancelButton: false, UIStyle.Orange, false, false);
            }
            else
            {
                //new Thread(new ParameterizedThreadStart(this.SaveAlarmToCVS)).Start(true);
                this.SaveAlarmToCVS(true);
            }
        }

        private void btMaterialSearch_Click(object sender, EventArgs e)
        {
            MaterialHistoryAllRows.Clear();
            if (this.threadMaterialSearch == null)
            {
                this.threadMaterialSearch = new Thread(new ThreadStart(this.MaterialHistoryRead));
            }
            if (this.threadMaterialSearch.ThreadState != ThreadState.Running)
            {
                if (this.threadMaterialSearch.ThreadState == ThreadState.Stopped)
                {
                    this.threadMaterialSearch = new Thread(new ThreadStart(this.MaterialHistoryRead));
                    this.threadMaterialSearch.Start();
                }
                else if (this.threadMaterialSearch.ThreadState == ThreadState.Stopped)
                {
                    this.threadMaterialSearch.Start();
                }
                else if (this.threadMaterialSearch.ThreadState == ThreadState.Unstarted)
                {
                    this.threadMaterialSearch.Start();
                }
            }
        }

        private void materialKeyWord_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Return)
            {
                this.btMaterialSearch_Click(this, null);
            }
        }

        private void MaterialHistoryPagination_PageChanged(object sender, object pagingSource, int pageIndex, int count)
        {
            if (MaterialHistoryPagination.TotalCount >= pageIndex * count)
            {
                List<MaterialHistoryDao> rows = MaterialHistoryAllRows.GetRange((pageIndex - 1) * count, count);
                LoadMaterialHistoryData(rows);
            }
            else
            {
                List<MaterialHistoryDao> rows = MaterialHistoryAllRows.GetRange((pageIndex - 1) * count, (MaterialHistoryPagination.TotalCount - ((pageIndex - 1) * count)));
                LoadMaterialHistoryData(rows);
            }
        }
        /// <summary>
        /// 异步导出指令历史记录到Excel表中
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="commandHistoryDaos"></param>
        public async Task ExportCommandHistoryToExcelAsync(string filePath, List<CommandHistoryDao> commandHistoryDaos)
        {
            if (!string.IsNullOrEmpty(filePath) && commandHistoryDaos != null)
            {
                await MiniExcel.SaveAsAsync(filePath, commandHistoryDaos);
            }
            else
            {
                UIMessageDialog.ShowMessageDialog("保存路径或保存数据为空！！", UILocalize.WarningTitle, showCancelButton: false, UIStyle.Orange, false, false);
            }
        }
        /// <summary>
        /// 异步导出报警历史记录到Excel表中
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="commandHistoryDaos"></param>
        public async Task ExportAlarmHistoryToExcelAsync(string filePath, List<AlarmHistoryDao> alarmHistoryDaos)
        {
            if (!string.IsNullOrEmpty(filePath) && alarmHistoryDaos != null)
            {
                await MiniExcel.SaveAsAsync(filePath, alarmHistoryDaos);
            }
            else
            {
                UIMessageDialog.ShowMessageDialog("保存路径或保存数据为空！！", UILocalize.WarningTitle, showCancelButton: false, UIStyle.Orange, false, false);
            }
        }
        /// <summary>
        /// 异步导出物料历史记录到Excel表中
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="commandHistoryDaos"></param>
        public async Task ExportMaterialHistoryToExcelAsync(string filePath, List<MaterialHistoryDao> materialHistoryDaos)
        {
            if (!string.IsNullOrEmpty(filePath) && materialHistoryDaos != null)
            {
                await MiniExcel.SaveAsAsync(filePath, materialHistoryDaos);
            }
            else
            {
                UIMessageDialog.ShowMessageDialog("保存路径或保存数据为空！！", UILocalize.WarningTitle, showCancelButton: false, UIStyle.Orange, false, false);
            }
        }
        private void MaterialPageSize_ValueChanged(object sender, int value)
        {
            MaterialHistoryPagination.PageSize = Convert.ToInt32(this.MaterialPageSize.Value);
        }

        private void btMaterialHistoryExportLog_Click(object sender, EventArgs e)
        {
            if (this.DGVMaterial.Rows.Count <= 0)
            {
                PopupNotice.DialogPopups("没有可保存的数据！！！", "There is no data to save!!!", enumPopupsType.Warning);
            }
            else
            {
                if (this.DGVMaterial.SelectedRows.Count == 0)
                {
                    PopupNotice.DialogPopups("请选择要保存的部分。[CTRL-A]为全选！！！", "Please select the section to save. [CTRL-A] Select All!!!", enumPopupsType.Warning);
                }
                else
                {
                    this.SaveMaterialToCVS(false);
                }
            }
        }

        private void btMaterialExportAllLog_Click(object sender, EventArgs e)
        {
            if (this.DGVMaterial.Rows.Count <= 0 || this.MaterialHistoryAllRows.Count <= 0)
            {
                UIMessageDialog.ShowMessageDialog("没有可保存的数据！！！", UILocalize.WarningTitle, showCancelButton: false, UIStyle.Orange, false, false);
            }
            else
            {
                this.SaveMaterialToCVS(true);
            }
        }
        /*        private void TableControl_Selecting(object sender, TabControlCancelEventArgs e)
{
string tabPageName = e.TabPage.Name;
if ("tabPage1".Equals(tabPageName))
{
e.Cancel = tabPage1CancelFlag;
}
else if ("AlarmHistory".Equals(tabPageName))
{
e.Cancel = AlarmHistoryCancelFlag;
}
else if ("MonitorDataHistory".Equals(tabPageName))
{
e.Cancel = MonitorDataHistoryCancelFlag;
}
}*/
    }
}
